package crmdna.sequence;

import static crmdna.common.OfyService.ofy;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.objectify.Work;

import crmdna.client.Client;
import crmdna.common.APIException;
import crmdna.common.APIResponse.Status;

class SequenceCore {
	static long getNext(final String client, String sequenceType) {
		List<Long> list = getNext(client, sequenceType, 1);
		return list.get(0);
	}

	static List<Long> getNext(final String client, final String type,
			final int numElements) {

		Client.ensureValidClient(client);

		if (numElements < 1)
			throw new APIException(Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED,
					"numElements should be > 0 when calling getNext in Sequence. Current value: ["
							+ numElements + "]");

		if ((type == null) || (type.equals("")))
			throw new APIException(
					Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED,
					"type cannot be null or empty string when calling getNext in Sequence. Current value: ["
							+ type + "]");

		List<Long> next = ofy(client).transact(new Work<List<Long>>() {

			@Override
			public List<Long> run() {
				String id = type.toUpperCase();
				SequenceEntity sequenceEntity = ofy(client).load()
						.type(SequenceEntity.class).id(id).get();

				if (null == sequenceEntity) {
					sequenceEntity = new SequenceEntity();
					sequenceEntity.id = id;
					sequenceEntity.counter = 0;
				}

				long initialValue = sequenceEntity.counter;
				List<Long> list = new ArrayList<Long>();
				for (Long i = 0l; i < numElements; i++)
					list.add(initialValue + i + 1);

				long finalValue = initialValue + numElements;
				sequenceEntity.counter = finalValue;
				ofy(client).save().entity(sequenceEntity).now();
				return list;
			}
		});

		return next;
	}
}